﻿/***************************************************************************
 * 文件名：MainForm
 * 功能：
 * 说明： 环境变量窗体
 * -------------------------------------------------------------------------
 * 创建时间：2025/7/9 08:50:43
 * 创建人：葛浩
 * 邮箱： 2094733071@qq.com
 * =========================================================================
 *
 * 修改人：   
 * 修改时间：   
 * 修改说明：   
 ***************************************************************************/
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Xml;
using Util;

namespace BuiltInTools
{
	public partial class EnviromentMainForm : XtraForm
	{
		#region Propertys

		/// <summary>
		/// 环境变量配置选择列表
		/// </summary>
		private List<EnviromentVariableConfiguration> EnvironmentVariableConfigurations = new List<EnviromentVariableConfiguration>();

		/// <summary>
		/// 环境变量项列表数据
		/// </summary>
		private List<EnvironmentVariableModel> EnvironmentVariables = new List<EnvironmentVariableModel>();

		/// <summary>
		/// 默认路径
		/// </summary>
		private string _defaultPath = string.Empty;

		#endregion

		#region Const

		/// <summary>
		/// 配置项文件名称
		/// </summary>
		private const string c_EnviromentVaribaleConfigurationFileName = "EnviromentVariableConfiguration.xml";

		/// <summary>
		/// 环境变量配置文件夹
		/// </summary>
		private const string c_EnviromentVariableDir = "EnviromentVariable";

		/// <summary>
		/// 文件夹名称
		/// </summary>
		private const string c_XML = "XML";

		/// <summary>
		/// 默认名称
		/// </summary>
		private const string c_PACKAGEHOME = "PACKAGEHOME";

		/// <summary>
		/// linq所在文件夹
		/// </summary>
		private const string c_nuget_groupFileSuffix = "nuget-group_index.json";

		/// <summary>
		/// linq缓存文件名称
		/// </summary>
		private const string c_list_urp_eframework_dallinq = "list_urp.eframework.dallinq.dat";

		/// <summary>
		/// data缓存文件名称
		/// </summary>
		private const string c_list_urp_common_data = "list_urp.common.data.dat";

		/// <summary>
		/// business缓存文件名称
		/// </summary>
		private const string c_list_urp_common_business = "list_urp.common.business.dat";

		/// <summary>
		/// v3_cahe环境变量名称
		/// </summary>
		private const string c_NUGET_HTTP_CACHE_PATH = "NUGET_HTTP_CACHE_PATH";

		#endregion

		#region Win

		public EnviromentMainForm()
		{
			InitializeComponent();
		}

		private void MainForm_Load(object sender, EventArgs e)
		{
			///初始化配置
			InitConfiguration();

			//加载配置
			LoadConfiguratiuon();

			//初始化下拉框控件
			InitSelectEnviromentCombox();
		}

		#endregion

		#region Methods

		/// <summary>
		/// 初始化环境变量配置
		/// </summary>
		private void InitConfiguration()
		{
			try
			{
				//获取当前用户的Local路径
				string appDataLocalPath = FileHelperUtil.GetAppDataFolderPath();
				if (string.IsNullOrEmpty(appDataLocalPath))
				{
					return;
				}

				//判断当前用户的环境变量的配置文件是否存在
				//若存在则不从本地程序中拷贝
				string fileDiretory = Path.Combine(appDataLocalPath, UtilConst.AuxiliaryTools, c_XML, c_EnviromentVariableDir);
				string filePath = Path.Combine(fileDiretory,c_EnviromentVaribaleConfigurationFileName);
				if (File.Exists(filePath))
				{
					return;
				}
				
				//检测程序目录是否为空
				Assembly assembly = Assembly.GetExecutingAssembly();
				string baseDiretory = assembly.Location.Replace(assembly.Modules?.FirstOrDefault().Name, "");
				if (string.IsNullOrEmpty(baseDiretory))
				{
					return;
				}

				//检测程序中的配置文件是否存在
				string enviromentVariableFilePath = Path.Combine(baseDiretory, c_EnviromentVariableDir, c_EnviromentVaribaleConfigurationFileName);
				if (!File.Exists(enviromentVariableFilePath))
				{
					return;
				}

				//文件目录若不存在，则创建目录
				if (!Directory.Exists(fileDiretory))
				{
					Directory.CreateDirectory(fileDiretory);
				}

				//拷贝文件
				File.Copy(enviromentVariableFilePath, filePath);

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 加载配置
		/// </summary>
		/// <param name="configurationName"></param>
		private void LoadConfiguratiuon(string configurationName = "")
		{
			if (string.IsNullOrEmpty(configurationName))
			{
				configurationName = c_PACKAGEHOME;
			}

			try
			{
				//获取当前用户的Local路径
				string appDataLocalPath = FileHelperUtil.GetAppDataFolderPath();
				if (string.IsNullOrEmpty(appDataLocalPath))
				{
					return;
				}

				//构建当前用户的环境变量配置文件
				string filePath = Path.Combine(appDataLocalPath, UtilConst.AuxiliaryTools, c_XML, c_EnviromentVariableDir, c_EnviromentVaribaleConfigurationFileName);
				if (!File.Exists(filePath))
				{
					return;
				}

				XmlDocument doc = new XmlDocument();
				doc.Load(filePath);
				if (doc == null)
				{
					return;
				}

				// 读取节点
				XmlNode root = doc.DocumentElement;
				if (root?.ChildNodes?.Count == 0)
				{
					return;
				}

				bool isNullEnvironmentVariableConfiguration = EnvironmentVariableConfigurations?.Count == 0;

				foreach (XmlNode childNode in root.ChildNodes)
				{
					if (childNode == null) { continue; }
					string enviromentVariableRootName = childNode.Attributes["Name"].Value;
					string defaultPath = childNode.Attributes["DefaultPath"].Value;
					if (string.IsNullOrEmpty(enviromentVariableRootName))
					{
						continue;
					}

					//初次加载时，添加下拉框配置项 
					if (isNullEnvironmentVariableConfiguration)
					{
						EnvironmentVariableConfigurations.Add(new EnviromentVariableConfiguration() { Name = enviromentVariableRootName });
					}

					if (!enviromentVariableRootName.Equals(configurationName))
					{
						continue;
					}
					else
					{
						txtFilePath.Text = defaultPath ?? "";
					}

					_defaultPath = defaultPath?.Trim();
					//首先添加根节点
					EnvironmentVariables.Add(new EnvironmentVariableModel() { VariableName = configurationName, VariableValue = defaultPath ?? "" });

					//如果存在子列表，遍历获取其他变量值
					foreach (XmlNode node in childNode.ChildNodes)
					{
						if (node == null) { continue; }
						string enviromentVariableName = node.Attributes["Name"].Value;
						string enviromentVariableValue = node.Attributes["Value"].Value;

						EnvironmentVariables.Add(new EnvironmentVariableModel()
						{
							VariableName = enviromentVariableName ?? "",
							VariableValue = enviromentVariableValue ?? ""
						});
					}
				}

				bsData.DataSource = EnvironmentVariables;
				gridControl1.MainView.RefreshData();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 初始化环境变量选择
		/// </summary>
		private void InitSelectEnviromentCombox()
		{
			///清空下拉列表
			cbxSelectEnviroment.Properties.Items?.Clear();

			if(EnvironmentVariableConfigurations?.Count == 0)
			{
				return;
			}

			///添加数据
			EnvironmentVariableConfigurations.ForEach(data =>
			{ 
				if (data == null || string.IsNullOrEmpty(data.Name))
				{
					return;
				}
				cbxSelectEnviroment.Properties.Items.Add(data.Name);
			});

			cbxSelectEnviroment.SelectedIndex = 0;
		}

		/// <summary>
		/// 创建目录
		/// </summary>
		/// <param name="variableName"></param>
		/// <param name="variableValue"></param>
		private void CreateEnviromentDiretory(string variableName, string variableValue)
		{
			try
			{
				string path = string.Empty;

				//若名称等于当前根目录，则直接检测是否存在此目录文件
				//若不存在则直接创建

				string configuratiuonName = cbxSelectEnviroment?.SelectedItem?.ToString();
				if (!variableName.Equals(configuratiuonName))
				{
					//如果是以ConfigurationName开头的，构建文件目录
					if (FileHelperUtil.IsMatchFixedBeginning(variableValue, configuratiuonName))
					{
						var paths = variableValue.Split('\\').ToList();
						if (paths?.Count() > 0)
						{
							for (int i = 0; i < paths.Count; i++)
							{
								//跳过第一个
								if (i == 0) { continue; }
								path += paths[i] + (i <= paths.Count - 1 ? "\\" : "");
							}
							path = Path.Combine(txtFilePath.Text.Trim(), path);
						}
					}
				}

				if (string.IsNullOrEmpty(path))
				{
					path = variableValue;
				}

				if (!Directory.Exists(path))
				{
					Directory.CreateDirectory(path);
				}
			}
			catch (Exception ex)
			{
				throw new Exception(ex.Message);
			}
		}

		/// <summary>
		/// 环境变量添加修改
		/// </summary>
		private void ChangeEnviromentVariable(EnvironmentVariableModel info = null)
		{
			try
			{
				//判断是否为添加数据行命令调用
				//如果是，则创建一个新的 ConstTypeInfo 实例
				bool isNullEnvironmentVariableInfo = info == null;

				if (isNullEnvironmentVariableInfo)
				{
					info = new EnvironmentVariableModel();
				}

				FMEnviromentVariableInfo fm = new FMEnviromentVariableInfo(info);
				DialogResult result = fm.ShowDialog();
				if (result != DialogResult.OK)
				{
					return;
				}

				if (isNullEnvironmentVariableInfo && EnvironmentVariables.Any(p => p.VariableName == info?.VariableName))
				{
					MessageBox.Show("列表中已存在此环境变量，不允许添加！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}
				//如果是添加操作，则将新的 ConstTypeInfo 实例添加到列表中
				if (isNullEnvironmentVariableInfo)
				{
					EnvironmentVariables.Add(info);
				}

				bsData.DataSource = EnvironmentVariables;
				gridControl1.MainView.RefreshData();
			}
			catch (Exception ex)
			{
				MessageBox.Show($"添加变量失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		#endregion

		#region Event

		#endregion

		/// <summary>
		/// 执行
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnExecute_Click(object sender, EventArgs e)
		{
			try
			{
				#region 验证信息

				string selectPath = txtFilePath.Text.Trim();

				//验证选择路径是否为空
				if (string.IsNullOrEmpty(selectPath))
				{
					MessageBox.Show("请选择文件夹路径", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				//如果当前选择路径不是默认路径，则验证当前文件夹是否存在
				if (!selectPath.Equals(_defaultPath) && !Directory.Exists(selectPath))
				{
					MessageBox.Show("当前选择的路径不存在，请重新选择", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				//检测是否以管理员权限运行
				if (!EnvironmentVariableUtil.IsAdministrator())
				{
					MessageBox.Show("请以管理员权限运行此程序", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				if (EnvironmentVariables.Count == 0)
				{
					return;
				}

				//检测是否满足规则
				string selectEnviroment = cbxSelectEnviroment?.SelectedItem?.ToString();
				if (string.IsNullOrEmpty(selectEnviroment))
				{
					return;
				}

				var variableModels = EnvironmentVariables.Where(p => p.VariableName.Equals(selectEnviroment));
				if (variableModels?.Count() == 0)
				{
					MessageBox.Show($"当前配置的环境变量不符合规则，请修改后重新执行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				var variableModel = variableModels.FirstOrDefault();
				//检查当前环境变量配置的是否存在盘符
				if (!FileHelperUtil.HasDriveLetter(variableModel.VariableValue))
				{
					MessageBox.Show($"环境变量{variableModel.VariableName}的环境变量值不合法！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				#endregion

				#region 添加系统环境变量

				foreach (var environment in EnvironmentVariables)
				{
					#region 在选择文件夹下创建目录

					string variableValue = environment.VariableValue;
					if (string.IsNullOrEmpty(variableValue))
					{
						continue;
					}

					//创建目录
					CreateEnviromentDiretory(environment.VariableName, environment.VariableValue);

					#endregion

					#region 添加环境变量

					//检测是否存在此环境变量
					if (EnvironmentVariableUtil.CheckExistEnvironmentVariable(environment.VariableName))
					{
						continue;
					}

					//添加系统环境变量
					EnvironmentVariableUtil.GeneratorEnvironmentVariable(environment.VariableName, environment.VariableValue);

					#endregion
				}

				MessageBox.Show("环境变量配置成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

				#endregion
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 添加环境变量
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnAddEnviiromentVariable_Click(object sender, EventArgs e)
		{
			ChangeEnviromentVariable();
		}

		/// <summary>
		///  清空列表
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnClear_Click(object sender, EventArgs e)
		{
			EnvironmentVariables.Clear();
			bsData.DataSource = EnvironmentVariables;
			gridControl1.MainView.RefreshData();
		}

		/// <summary>
		/// 环境变量改变事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void cbxSelectEnviroment_SelectedValueChanged(object sender, EventArgs e)
		{
			cbxSelectEnviroment.SelectedValueChanged -= cbxSelectEnviroment_SelectedValueChanged;

			if(cbxSelectEnviroment == null|| cbxSelectEnviroment.SelectedItem == null)
			{
				return;
			}

			EnvironmentVariables.Clear();
			LoadConfiguratiuon(cbxSelectEnviroment.SelectedItem.ToString());

			cbxSelectEnviroment.SelectedValueChanged += cbxSelectEnviroment_SelectedValueChanged;
		}

		/// <summary>
		///  选择文件路径
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnSelectFilePath_Click(object sender, EventArgs e)
		{
			try
			{
				string folderPath = string.Empty;
				using (var folderDialog = new FolderBrowserDialog())
				{
					folderDialog.Description = "请选择文件夹";
					folderDialog.ShowNewFolderButton = true; // 允许新建文件夹

					if (folderDialog.ShowDialog() != DialogResult.OK)
					{
						return;
					}

					folderPath = folderDialog.SelectedPath;
				}

				//构建PACKAGEHOME路径
				if (EnvironmentVariables?.Count <= 0 || cbxSelectEnviroment?.SelectedItem == null)
				{
					return;
				}

				foreach (var environment in EnvironmentVariables)
				{
					if (environment == null || environment.VariableName != cbxSelectEnviroment.SelectedItem.ToString())
					{
						continue;
					}

					environment.VariableValue = folderPath;
				}

				txtFilePath.Text = folderPath;

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 右键菜单显示事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void gridView1_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
		{
			// 检查是否是右键点击
			if (e.HitInfo.InRowCell)
			{
				// 显示您的 ContextMenuStrip
				contextMenuStrip1.Show(Cursor.Position);
			}
		}

		/// <summary>
		/// 删除环境变量
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnDelete_Click(object sender, EventArgs e)
		{
			try
			{
				var gridView = gridControl1.MainView as GridView;
				if (gridView == null)
				{
					return;
				}

				var selectedRow = gridView.GetFocusedRow() as EnvironmentVariableModel;
				
				if (selectedRow == null)
				{
					MessageBox.Show("请选择要删除的环境变量。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
					return;
				}

				if (MessageBox.Show($"确定要删除环境变量：{selectedRow.VariableName} 吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
				{
					EnvironmentVariables.Remove(selectedRow);
				}

				bsData.DataSource = EnvironmentVariables;
				gridControl1.MainView.RefreshData();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 双击事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void gridControl1_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			try
			{
				var gridView = gridControl1.MainView as GridView;
				if (gridView == null)
				{
					return;
				}

				var selectedRow = gridView.GetFocusedRow() as EnvironmentVariableModel;

				if (selectedRow == null)
				{
					MessageBox.Show("请选择要删除的环境变量。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
					return;
				}

				ChangeEnviromentVariable(selectedRow);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
	}
}
